package br.pucrs.lognplay.job;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import br.pucrs.lognplay.entity.StaticView;
import br.pucrs.lognplay.repository.RepositoryManager;
import br.pucrs.lognplay.repository.StaticViewRepository;

public class StaticIndexerControllerJob implements Job {

	private static final Logger logger = Logger.getLogger(StaticIndexerControllerJob.class);

	private static final String STATIC_INDEXER_JOB_NAME = "STATIC_INDEXER_JOB";

	private static final String STATIC_INDEXER_TRIGGER_NAME = "STATIC_INDEXER_TRIGGER";

	private static final String STATIC_INDEXER_GROUP_NAME = "STATIC_INDEXER_GROUP";

	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		logger.trace("=== Executing StaticIndexerControllerJob...");

		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

			RepositoryManager.beginTransaction();
			StaticViewRepository staticViewRepository = RepositoryManager.getStaticViewRepository();
			List<StaticView> staticViews = staticViewRepository.listAll();
			RepositoryManager.commitTransaction();

			if (staticViews.size() > 0) {
				for (StaticView staticView : staticViews) {

					logger.trace("Processing static view id: " + staticView.getId());

					// @formatter:off
					JobDetail staticIndexerJob = newJob(StaticIndexerJob.class)
							.withIdentity(STATIC_INDEXER_JOB_NAME + "#" + staticView.getId(), STATIC_INDEXER_GROUP_NAME)
							.build();
	
					Trigger staticIndexerTrigger = newTrigger()
							.withIdentity(STATIC_INDEXER_TRIGGER_NAME + "#" + staticView.getId(), STATIC_INDEXER_GROUP_NAME)
							.startNow()
							.build();
					// @formatter:on
					staticIndexerJob.getJobDataMap().put(StaticIndexerJob.STATIC_VIEW_ID_PARAMETER, staticView.getId());
					if (!scheduler.checkExists(staticIndexerJob.getKey())) {
						scheduler.scheduleJob(staticIndexerJob, staticIndexerTrigger);
					}
				}
			} else {
				logger.trace("No static views to process!");
			}

		} catch (Exception e) {
			logger.error(e);
		}

		logger.trace("=== StaticIndexerControllerJob terminated!");
	}
}
